package com.jackchen.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
	// ----------------------------------------------------------
	// ip处理类
	// ----------------------------------------------------------

	/**
	 * 把ip地址格式化为：000.000.000.000
	 * 
	 * @param ip
	 * @return 返回规格ip
	 */
	public static String strfullip(String ip) {
		StringBuffer buff = new StringBuffer();
		buff.append("");
		String strzero = "000";
		int ilen = 0;
		if (ip != null) {
			String[] arrip = ip.split("\\.");
			if (arrip.length == 4) {
				for (int i = 0; i < 4; i++) {
					if (i == 0) {
						ilen = arrip[i].length();
						if (ilen < 3) {
							buff.append(strzero.substring(0, 3 - ilen)).append(
									arrip[i]);
						} else {
							buff.append(arrip[i]);
						}
					} else {
						ilen = arrip[i].length();
						if (ilen < 3) {
							buff.append(".")
									.append(strzero.substring(0, 3 - ilen))
									.append(arrip[i]);
						} else {
							buff.append(".").append(arrip[i]);
						}
					}
				}
			}
		}
		return buff.toString();
	}
	/**
	 * 在字符串source中，用to替换from
	 * 
	 * @param from
	 * @param to
	 * @param source
	 * @return
	 */
	public static String replace(String from, String to, String source) {
		if (source == null || from == null || to == null)
			return null;
		StringBuffer str = new StringBuffer("");
		int index = -1;
		while ((index = source.indexOf(from)) != -1) {
			str.append(source.substring(0, index) + to);
			source = source.substring(index + from.length());
			index = source.indexOf(from);
		}
		str.append(source);
		return str.toString();
	}
	/**
	 * 将字符串 source 中的 oldStr 替换为 newStr, matchCase 为是否设置大小写敏感查找
	 * 
	 * @param source
	 *            需要替换的源字符串
	 * @param oldStr
	 *            需要被替换的老字符串
	 * @param newStr
	 *            替换为的新字符串
	 * @param matchCase
	 *            是否需要按照大小写敏感方式查找
	 */
	public static String replace2(String source, String oldStr, String newStr,
			boolean matchCase) {
		if (source == null) {
			return null;
		}
		// 首先检查旧字符串是否存在, 不存在就不进行替换
		if (source.toLowerCase().indexOf(oldStr.toLowerCase()) == -1) {
			return source;
		}
		int findStartPos = 0;
		int a = 0;
		while (a > -1) {
			int b = 0;
			String str1, str2, str3, str4, strA, strB;
			str1 = source;
			str2 = str1.toLowerCase();
			str3 = oldStr;
			str4 = str3.toLowerCase();
			if (matchCase) {
				strA = str1;
				strB = str3;
			} else {
				strA = str2;
				strB = str4;
			}
			a = strA.indexOf(strB, findStartPos);
			if (a > -1) {
				b = oldStr.length();
				findStartPos = a + b;
				StringBuffer bbuf = new StringBuffer(source);
				source = bbuf.replace(a, a + b, newStr) + "";
				// 新的查找开始点位于替换后的字符串的结尾
				findStartPos = findStartPos + newStr.length() - b;
			}
		}
		return source;
	}
	public static String toGb(String uniStr){     String gbStr = "";     if(uniStr == null){   uniStr = "";     }     try{   byte[] tempByte = uniStr.getBytes("ISO8859_1");   gbStr = new String(tempByte,"UTF-8");     }  catch(Exception ex){    }     return gbStr; }
	public static String toUni(String gbStr){     String uniStr = "";     if(gbStr == null){   gbStr = "";     }     try{   byte[] tempByte = gbStr.getBytes("UTF-8");   uniStr = new String(tempByte,"ISO8859_1");     }catch(Exception ex){    }    return uniStr; }

	public static String htmlencode(String str) {
		if (str == null) {
			return null;
		}
		return replace("'", "", replace("<", "<", str));
	}

	public static String htmldecode(String str) {
		if (str == null) {
			return null;
		}

		return replace("'", "", replace("<", "<", str));
	}

	private static final String _BR = "";

	public static String htmlshow(String str) {
		if (str == null) {
			return null;
		}
		str = replace("<", "<", str);
		str = replace(" ", " ", str);
		str = replace("\r\n", _BR, str);
		str = replace("\n", _BR, str);
		str = replace("\t", "    ", str);
		return str;
	}
	/**
	 * 返回指定字节长度字符串
	 * 
	 * @param str
	 * @param length
	 * @return
	 */
	public static String toLength(String str, int length) {
		if (str == null) {
			return null;
		}
		if (length <= 0) {
			return "";
		}
		try {
			if (str.getBytes("GBK").length <= length) {
				return str;
			}
		} catch (Exception e) {
		}
		StringBuffer buff = new StringBuffer();

		int index = 0;
		char c;
		length -= 3;
		while (length > 0) {
			c = str.charAt(index);
			if (c < 128) {
				length--;
			} else {
				length--;
				length--;
			}
			buff.append(c);
			index++;
		}
		buff.append("...");
		return buff.toString();
	}
	// -----------------------------------------------------
		// 金额转换
		// -----------------------------------------------------
		/**
		 * 人民币转换成大写
		 * 
		 * @param str
		 * @return
		 */
		public static String hangeToBig(String str) {
			double value;
			try {
				value = Double.parseDouble(str.trim());
			} catch (Exception e) {
				return null;
			}
			char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示
			char[] vunit = { '万', '亿' }; // 段名表示
			char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示
			long midVal = (long) (value * 100); // 转化成整形
			String valStr = String.valueOf(midVal); // 转化成字符串

			String head = valStr.substring(0, valStr.length() - 2); // 取整数部分
			String rail = valStr.substring(valStr.length() - 2); // 取小数部分

			String prefix = ""; // 整数部分转化的结果
			String suffix = ""; // 小数部分转化的结果
			// 处理小数点后面的数
			if (rail.equals("00")) { // 如果小数部分为0
				suffix = "整";
			} else {
				suffix = digit[rail.charAt(0) - '0'] + "角"
						+ digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来
			}
			// 处理小数点前面的数
			char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
			char zero = '0'; // 标志'0'表示出现过0
			byte zeroSerNum = 0; // 连续出现0的次数
			for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字
				int idx = (chDig.length - i - 1) % 4; // 取段内位置
				int vidx = (chDig.length - i - 1) / 4; // 取段位置
				if (chDig[i] == '0') { // 如果当前字符是0
					zeroSerNum++; // 连续0次数递增
					if (zero == '0') { // 标志
						zero = digit[0];
					} else if (idx == 0 && vidx > 0 && zeroSerNum < 4) {
						prefix += vunit[vidx - 1];
						zero = '0';
					}
					continue;
				}
				zeroSerNum = 0; // 连续0次数清零
				if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的
					prefix += zero;
					zero = '0';
				}
				prefix += digit[chDig[i] - '0']; // 转化该数字表示
				if (idx > 0)
					prefix += hunit[idx - 1];
				if (idx == 0 && vidx > 0) {
					prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
				}
			}
			if (prefix.length() > 0)
				prefix += '圆'; // 如果整数部分存在,则有圆的字样
			return prefix + suffix; // 返回正确表示
		}
		/**
		 * 数字金额表达式
		 * 
		 * @param num
		 * @return
		 */
		public static String convertNumToMoney(int num) {
			NumberFormat formatc = NumberFormat.getCurrencyInstance(Locale.CHINA);
			String strcurr = formatc.format(num);
			System.out.println(strcurr);
			// num = NumberFormat.getInstance().setParseIntegerOnly(true));
			return strcurr;
		}
		// ------------------------------------------------------------------------------
		// 特殊字符串处理
		// -------------------------------------------------------------------------------
		/**
		 * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串
		 * 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&'
		 * 
		 * @param strSrc
		 *            要进行替换操作的字符串
		 * @return 替换特殊字符后的字符串
		 * @since 1.0
		 */
		public static String htmlEncode(String strSrc) {
			if (strSrc == null)
				return "";

			char[] arr_cSrc = strSrc.toCharArray();
			StringBuffer buf = new StringBuffer(arr_cSrc.length);
			char ch;

			for (int i = 0; i < arr_cSrc.length; i++) {
				ch = arr_cSrc[i];

				if (ch == '<')
					buf.append("&lt;");
				else if (ch == '>')
					buf.append("&gt;");
				else if (ch == '"')
					buf.append("&quot;");
				else if (ch == '\'')
					buf.append("&#039;");
				else if (ch == '&')
					buf.append("&amp;");
				else
					buf.append(ch);
			}

			return buf.toString();
		}
		/**
		 * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串
		 * 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&'
		 * 
		 * @param strSrc
		 *            要进行替换操作的字符串
		 * @param quotes
		 *            为0时单引号和双引号都替换，为1时不替换单引号，为2时不替换双引号，为3时单引号和双引号都不替换
		 * @return 替换特殊字符后的字符串
		 * @since 1.0
		 */
		public static String htmlEncode(String strSrc, int quotes) {

			if (strSrc == null)
				return "";
			if (quotes == 0) {
				return htmlEncode(strSrc);
			}

			char[] arr_cSrc = strSrc.toCharArray();
			StringBuffer buf = new StringBuffer(arr_cSrc.length);
			char ch;

			for (int i = 0; i < arr_cSrc.length; i++) {
				ch = arr_cSrc[i];
				if (ch == '<')
					buf.append("&lt;");
				else if (ch == '>')
					buf.append("&gt;");
				else if (ch == '"' && quotes == 1)
					buf.append("&quot;");
				else if (ch == '\'' && quotes == 2)
					buf.append("&#039;");
				else if (ch == '&')
					buf.append("&amp;");
				else
					buf.append(ch);
			}

			return buf.toString();
		}

		// ---------------------------------------------------------
		// 字符串处理
		// ------------------------------------------------------------

		/**
		 * 去掉字符串中重复子字符串
		 * 
		 * @param str
		 * @return
		 */
		@SuppressWarnings("unused")
		private static String removeSameString(String str) {
			Set mLinkedSet = new LinkedHashSet();// set集合的特征：其子集不可以重复
			String[] strArray = str.split(" ");// 根据空格(正则表达式)分割字符串
			StringBuffer sb = new StringBuffer();

			for (int i = 0; i < strArray.length; i++) {
				if (!mLinkedSet.contains(strArray[i])) {
					mLinkedSet.add(strArray[i]);
					sb.append(strArray[i] + " ");
				}
			}
			System.out.println(mLinkedSet);
			return sb.toString();
		}

		/**
		 * 杀空函数，将"null"和null对象转换为""
		 * 
		 * @param str
		 *            输入字符串 * @return 输出字符串
		 */
		public String killNull(String str) {
			String returnStr = null;
			if (str == null || "null".equals(str.toLowerCase())) {
				returnStr = "";
			} else {
				returnStr = str;
			}
			return returnStr;
		}

		/**
		 * 切割字符串
		 * 
		 * @param args
		 */
		public String timeFirs() {
			String[] timefirs = new String[3];
			String timefir = "2006-9-28";
			timefirs = timefir.split("-");
			String mydate1 = timefirs[0] + "年" + timefirs[1] + "月" + timefirs[2]
					+ "日";
			return mydate1;
		}

		/****
		 * 判断字符串是否为空，并删除首尾空格
		 * 
		 */
		public static String convertNullCode(String tempSql) {
			if (tempSql == null)
				tempSql = "";
			return tempSql;
		}
		/****
		 * 替换非法字符
		 * 
		 * @param input
		 * @return
		 */
		public static String convertHtml(String input) {
			StringBuffer returnString = new StringBuffer(input.length());

			char ch = ' ';
			for (int i = 0; i < input.length(); i++) {

				ch = input.charAt(i);

				if (ch == '<') {
					returnString = returnString.append("&lt");
				} else if (ch == '>') {
					returnString = returnString.append("&gt");
				} else if (ch == ' ') {
					returnString = returnString.append("&nbsp");
				} else if (ch == '\\') {
					returnString = returnString.append("&acute");
				} else {
					returnString = returnString.append(ch);
				}
			}
			return returnString.toString();
		}

		/**
		 * 将String类型变量转换为ASCII码 1、如果ASCII为73<i>、79[O]，跳过
		 * 只转换'0-9'和'A-Z'(除'I'、'O')的ASCII码，对应的ASCII码为'48-57'和'65-90'(除'73'、'79')
		 * 
		 * @param transParam
		 *            待转换的变
		 * @return 转换后的ASCII码
		 */
		public static String stringToASCII(String transParam) {
			// 不满足要求，直接返回null
			if (transParam == null || transParam.length() == 0) {
				return null;
			}
			char[] transChars = transParam.toCharArray();
			String ascii = "";
			// 字符转换为数字，并拼接为ASCII码
			int charASCII = -1;
			for (int i = 0; i < transChars.length; i++) {
				// charASCII = (int) transChars<i>;
				// 如果为73(I)、79(O)，自增
				if (charASCII == 73 || charASCII == 79) {
					charASCII++;
				}
				ascii += charASCII;
			}
			return ascii;
		}
		// -------------------------------------------------------
		//              字符编码工具类
		// -------------------------------------------------------
		/**
		 * 代码转换，GBK转换为ISO-8859-1
		 * 
		 * @param tempSql
		 *            要转换的字符串
		 * @return
		 */
		public static String ISOCode(String tempSql) {

			String returnString = convertNullCode(tempSql);

			try {
				byte[] ascii = returnString.getBytes("GBK");
				returnString = new String(ascii, "ISO-8859-1");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return returnString;
		}
		/**
		   * utf8URL编码转字符
		   * @param text
		   * @return
		   */
		  private static final String CodeToWord(String text) {
		    String result;

		    if (Utf8codeCheck(text)) {
		      byte[] code = new byte[3];
		      code[0] = (byte) (Integer.parseInt(text.substring(1, 3), 16) - 256);
		      code[1] = (byte) (Integer.parseInt(text.substring(4, 6), 16) - 256);
		      code[2] = (byte) (Integer.parseInt(text.substring(7, 9), 16) - 256);
		      try {
		        result = new String(code, "UTF-8");
		      }catch (UnsupportedEncodingException ex) {
		        result = null;
		      }
		    }
		    else {
		      result = text;
		    }

		    return result;
		  }
		  /**
		   * 编码是否有效
		   * @param text
		   * @return
		   */
		  private static final boolean Utf8codeCheck(String text){
		    String sign = "";
		    if (text.startsWith("%e"))
		      for (int i = 0, p = 0; p != -1; i++) {
		        p = text.indexOf("%", p);
		        if (p != -1)
		          p++;
		        sign += p;
		      }
		    return sign.equals("147-1");
		  }

		  /**
		   * 判断是否Utf8Url编码
		   * @param text
		   * @return
		   */
		  public static final boolean isUtf8Url(String text) {
		    text = text.toLowerCase();
		    int p = text.indexOf("%");
		    if (p != -1 && text.length() - p > 9) {
		      text = text.substring(p, p + 9);
		    }
		    return Utf8codeCheck(text);
		  }
	  

		/**
		 * 代码转换，ISO-8859-1转换为GBK
		 * 
		 * @param tempSql
		 *            要转换的字符串
		 * @return
		 */
		public static String GBKCode(String tempSql) {
			String returnString = convertNullCode(tempSql);
			try {
				byte[] ascii = returnString.getBytes("ISO-8859-1");
				returnString = new String(ascii, "GBK");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return returnString;
		}
		/**
		 * 代码转换 从srcCode转换为destCode
		 * 
		 * @param srcCode
		 *            原编码
		 * @param destCode
		 *            目标编码
		 * @param strTmp
		 *            要转换的字符串
		 * @return
		 */
		public static String convertCode(String srcCode, String destCode,
				String strTmp) {
			String returnString = convertNullCode(strTmp);
			try {
				byte[] ascii = returnString.getBytes(srcCode);
				returnString = new String(ascii, destCode);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return returnString;
		}

		/**
		 * 代码转换，GBK转换为big5
		 * 
		 * @param tempSql
		 *            要转换的字符串
		 * @return
		 */
		public static String GBK2BIG5Code(String tempSql) {
			String returnString = convertNullCode(tempSql);
			try {
				byte[] ascii = returnString.getBytes("GBK");
				returnString = new String(ascii, "big5");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return returnString;
		}
		/**
		 * @param strVal
		 *            要转换的字符串
		 * @return 从“ISO8859_1”到“GBK”得到的字符串
		 * @since 1.0
		 */
		public static String toChinese(String strVal) {
			try {
				if (strVal == null) {
					return "";
				} else {
					strVal = strVal.trim();
					strVal = new String(strVal.getBytes("ISO8859_1"), "GBK");
					return strVal;
				}
			} catch (Exception exp) {
				return "";
			}
		}

		/**
		 * @param strVal
		 *            要转换的字符串
		 * @return 从“GBK”到“ISO8859_1”得到的字符串
		 * @since 1.0
		 */
		public static String toISO(String strVal) {
			try {
				if (strVal == null) {
					return "";
				} else {
					strVal = new String(strVal.getBytes("GBK"), "ISO8859_1");
					return strVal;
				}
			} catch (Exception exp) {
				return "";
			}
		}

		// -----------------------------------------------------------------------
		//            基本类型与String
		// ------------------------------------------------------------------------
		/**
		 * String型变量转换成int型变量
		 * 
		 * @param str
		 *            要进行转换的字符串
		 * @return intVal 如果str不可以转换成int型数据，返回-1表示异常,否则返回转换后的值
		 * @since 1.0
		 */
		public static int str2Int(String str) {
			int intVal;

			try {
				intVal = Integer.parseInt(str);
			} catch (Exception e) {
				intVal = 0;
			}

			return intVal;
		}

		public static double str2Double(String str) {
			double dVal = 0;

			try {
				dVal = Double.parseDouble(str);
			} catch (Exception e) {
				dVal = 0;
			}

			return dVal;
		}

		public static long str2Long(String str) {
			long longVal = 0;

			try {
				longVal = Long.parseLong(str);
			} catch (Exception e) {
				longVal = 0;
			}

			return longVal;
		}

		public static float stringToFloat(String floatstr) {
			Float floatee;
			floatee = Float.valueOf(floatstr);
			return floatee.floatValue();
		}	
		// change the float type to the string type
		public static String floatToString(float value) {
			Float floatee = new Float(value);
			return floatee.toString();
		}

		/**
		 * int型变量转换成String型变量
		 * 
		 * @param intVal
		 *            要进行转换的整数
		 * @return str 如果intVal不可以转换成String型数据，返回空值表示异常,否则返回转换后的值
		 */
		public static String int2Str(int intVal) {
			String str;

			try {
				str = String.valueOf(intVal);
			} catch (Exception e) {
				str = "";
			}

			return str;
		}

		/**
		 * long型变量转换成String型变量
		 * 
		 * @param longVal
		 *            要进行转换的整数
		 * @return str 如果longVal不可以转换成String型数据，返回空值表示异常,否则返回转换后的值
		 */
		public static String long2Str(long longVal) {
			String str;

			try {
				str = String.valueOf(longVal);
			} catch (Exception e) {
				str = "";
			}

			return str;
		}
		// -------------------------------------------------------------------
		//                       null处理
		// --------------------------------------------------------------------
		/**
		 * 把null值和""值转换成&nbsp; 主要应用于页面表格格的显示
		 * 
		 * @param str
		 *            要进行处理的字符串
		 * @return 转换后的字符串
		 */
		public static String str4Table(String str) {
			if (str == null)
				return "&nbsp;";
			else if (str.equals(""))
				return "&nbsp;";
			else
				return str;
		}

		/**
		 * null 处理
		 * 
		 * @param str
		 *            要进行转换的字符串
		 * @return 如果str为null值，返回空串"",否则返回str
		 */
		public static String null2Blank(String str) {
			if (str == null)
				return "";
			else
				return str;
		}

		/**
		 * null 处理
		 * 
		 * @param d
		 *            要进行转换的日期对像
		 * @return 如果d为null值，返回空串"",否则返回d.toString()
		 */

		public static String null2Blank(Date d) {
			if (d == null)
				return "";
			else
				return d.toString();
		}

		
		/**
		 * null 处理
		 * 
		 * @param str
		 *            要进行转换的字符串
		 * @return 如果str为null值，返回空串整数0,否则返回相应的整数
		 */
		public static int null2Zero(String str) {
			int intTmp;
			intTmp = str2Int(str);
			if (intTmp == -1)
				return 0;
			else
				return intTmp;
		}

		/**
		 * 把null转换为字符串"0"
		 * 
		 * @param str
		 * @return
		 */
		public static String null2SZero(String str) {
			str = StringUtil.null2Blank(str);
			if (str.equals(""))
				return "0";
			else
				return str;
		}
		//-------------------------------------------------------------
		//                         main函数测试
		//-------------------------------------------------------------
		
		public static void main(String[] args) {
			String source = "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg";
			String from = "efg";
			String to = "房贺威";
			System.out.println("在字符串source中，用to替换from，替换结果为："
					+ replace(from, to, source));
			System.out.println("返回指定字节长度的字符串："
					+ toLength("abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg", 9));
			System.out.println("人民币转换成大写：" + hangeToBig("10019658"));
			System.out.println("去掉字符串中重复的子字符串：" + removeSameString("100 100 9658"));
			// 测试ip
			String strip = "202.108.33.32";
			System.out.println(StringUtil.strfullip(strip));
			System.out.println(System.currentTimeMillis());
			System.out.println(System.currentTimeMillis());
			// String转ascii
			String s1 = "你好";
			char[] c1 = s1.toCharArray();
			for (int i = 0; i < c1.length; i++) {
				System.out.println(c1[i] + ":" + (int) c1[i]);
			}
			String s = "22307 35806 24555 20048";// ASCII码
			String[] chars = s.split(" ");
			for (int j = 0; j < chars.length; j++) {
				System.out.println(chars[j] + ":"
						+ (char) Integer.parseInt(chars[j]));
			}
			System.out.println("--------------------------------");
			String s2 = "22909";
			System.out.println(s2 + ":" + (char) Integer.parseInt(s2));
			// 金额 ￥1,234,556.00
			StringUtil.convertNumToMoney(1234566);

		  }
		
		}


